package org.com.coolfish.service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.com.coolfish.common.database.entity.KuyuAddPackage;
import org.com.coolfish.common.database.entity.KuyuAgent;
import org.com.coolfish.common.database.entity.KuyuAgentAccount;
import org.com.coolfish.common.database.entity.KuyuCard;
import org.com.coolfish.common.database.entity.KuyuCardMoney;
import org.com.coolfish.common.database.entity.KuyuOperator;
import org.com.coolfish.common.database.entity.KuyuPackage;
import org.com.coolfish.common.database.entity.KuyuPackagePrice;
import org.com.coolfish.common.database.entity.kuyuAgentCommission;
import org.com.coolfish.common.database.service.KuyuAddPackageService;
import org.com.coolfish.common.database.service.KuyuAgentService;
import org.com.coolfish.common.database.service.KuyuCardMoneyService;
import org.com.coolfish.common.database.service.KuyuCardService;
import org.com.coolfish.common.database.service.KuyuOperatorService;
import org.com.coolfish.common.database.service.KuyuPackagePriceService;
import org.com.coolfish.common.database.service.KuyuPackageService;
import org.com.coolfish.common.database.service.kuyuAgentAccountService;
import org.com.coolfish.common.database.service.kuyuAgentCommissionService;
import org.com.coolfish.common.message.MsisdnCardMessage;
import org.com.coolfish.common.model.DisabledBean;
import org.com.coolfish.common.util.DecimalTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

/***
 * 
 * @author HUSHENG
 * @desc 中国移动的http get 请求API
 *
 */
@Service
public class CMCCCardStopService {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private KuyuCardService kuyuCardService;
	@Autowired
	private KuyuPackagePriceService kuyuPackagePriceService;
	@Autowired
	private KuyuAgentService kuyuAgentService;
	@Autowired
	private kuyuAgentCommissionService kuyuAgentCommissionService;
	@Autowired
	private KuyuAddPackageService kuyuAddPackageService;
	@Autowired
	private KuyuPackageService kuyuPackageService;
	@Autowired
	private KuyuCardMoneyService kuyuCardMoneyService;
	@Autowired
	private KuyuOperatorService kuyuOperatorService;
	@Autowired
	private kuyuAgentAccountService  kuyuAgentAccountService;
	// 移动停机
	public void handle(MsisdnCardMessage message) {

		// 02或6类卡
		List<Integer> operatoridList = Arrays.asList(185, 188, 191, 193, 226, 160, 170, 182, 204);
		Integer operatorid = message.getOperatorid();

		logger.info("处理号码[{}], operatorid[{}]", message.getTel(), operatorid);

		List<KuyuAddPackage> addPackage = new ArrayList<>();
		
		addPackage = kuyuAddPackageService.findStopCorrelation(message.getCardid(),TimeService.nextMonthFirstDay(),TimeService.nextMonthLastDay());
		
		// 通过队列给过来的tel查询电信号码类型
		if (!operatoridList.contains(operatorid)) {
			logger.info("非02/06类号码[{}]订购的套餐[{}]", message.getTel(), addPackage);

			// 非正常卡根据查询是否有订购套餐來停机
			if (null ==addPackage || addPackage.size() == 0) {

				// 查找上级代理商
				List<KuyuCard> findAgentMessage = kuyuCardService.findAgentMessage(message.getTel());

				KuyuPackagePrice kuyuPackagePrice = null;
				for (KuyuCard kuyuCard : findAgentMessage) {
					logger.info("fid[{}]sid[{}]tid[{}]", kuyuCard.getFid(), kuyuCard.getSid(), kuyuCard.getTid());
					// 查看是否有代理商
					if (kuyuCard.getTid() > 0) {
						
						kuyuPackagePrice = kuyuPackagePriceService
								.findTidPackagePriceCardMessage(message.getPackageid(), kuyuCard.getTid());
						
						find(message, kuyuPackagePrice);
						
					} else if (kuyuCard.getSid() > 0) {
						
						kuyuPackagePrice = kuyuPackagePriceService
								.findSidPackagePriceCardMessage(message.getPackageid(), kuyuCard.getSid());
						
						find(message, kuyuPackagePrice);
						
					} else if (kuyuCard.getFid() > 0) {
						
						kuyuPackagePrice = kuyuPackagePriceService
								.findFidPackagePriceCardMessage(message.getPackageid(), kuyuCard.getFid());

						if (null != kuyuPackagePrice) {
							
							find(message, kuyuPackagePrice);
						} else {
							logger.info("供应商没有找到对应的套餐,查找自己售出套餐----------");
							//没有代理商
							noAgent(message, kuyuPackagePrice);
						}
						
					} else {
						//没有代理商
						noAgent(message, kuyuPackagePrice);
					}
				}
			}else {
			logger.info("非02/06类号码有订购无需操作[{}]",message.getTel());
			}
		} else {
			addPackage = kuyuAddPackageService.findStopCorrelation(message.getCardid(),TimeService.nextMonthFirstDay(),TimeService.nextMonthLastDay());
			// 正常卡根据查詢是否有订购套餐來停机,没订购进行停机
			if (null == addPackage  || addPackage.size() == 0) {
				logger.info("移动02或6类号码[{}]未订购下月套餐进行停机操作：" + message.getTel());
				//disabledNumberController(message);
			}else {
			logger.info("02/06类号码有订购套餐无需操作[{}]",message.getTel());
			}
		}
		

	}
	private void noAgent(MsisdnCardMessage message, KuyuPackagePrice kuyuPackagePrice) {
		KuyuPackage findPackagePrice = kuyuPackageService.findPackagePrice(message.getPackageid());
		logger.info("非02/06类号码[{}]套餐价格[{}]", message.getTel(), kuyuPackagePrice);
		if (null != findPackagePrice) {
			DecimalFormat df1 = new DecimalFormat("0.00");
			// 号码账户余额
			String amount = df1.format(message.getAmount());
			// 套餐订购价格

			String packgePrice = findPackagePrice.getPrice().toString(); 
			// 用户余额 - 套餐订购价格
			double priceDifference = DecimalTools.sub(amount, packgePrice);
			logger.info("号码[{}], 账户余额[{}], 套餐订购价格[{}], 差额[{}]", message.getTel(), amount,
					packgePrice, priceDifference);
			// 余额不够,停机处理
			if (Double.parseDouble(amount) <= 0 || priceDifference < 0) {
				logger.info("号码[{}], 余额[{}], 余额不够进行停机操作：", message.getTel(), amount);

				//disabledNumberController(message);
			} else {
				/**
				 * 111
				 */
				// 扣除余额
				//orderPackage(kuyuPackagePrice, priceDifference, message);
				//生成对应的扣费记录
				saveRecordOfDeductions(message, priceDifference);
				// 扣除余额
				kuyuCardService.orderForTheNextMonth(BigDecimal.valueOf(priceDifference), message.getTel());
				// 订购次数加1
				kuyuCardService.deductions(message.getFrequency() + 1, message.getTel());
				//订购
				logger.info("号码[{}],生成相应的消费记录,----- 进行订购操作：", message.getTel());
				//orderPackageService.onMonth(message);
				// isStartUp(message);
				saveNextMontOrder(message);
			}
		}
		
	}
	/*
	 * 次月订单生成
	 */
	private void saveNextMontOrder(MsisdnCardMessage message) {
		KuyuOperator operator = kuyuOperatorService.findOperatorLid(message.getOperatorid());
		KuyuPackage kuyuPackage = kuyuPackageService.getPropert(message.getPackageid());
		KuyuAddPackage kuyu;
		kuyu = new KuyuAddPackage();
		
		kuyu.setCard(message.getTel());
		kuyu.setCardId(message.getCardid());
		kuyu.setDid(0);
		kuyu.setFinalprice(kuyuPackage.getPrice());
		kuyu.setOperatorName(operator.getName());
		kuyu.setPackageid(kuyuPackage.getId());
		kuyu.setPid(0);
		kuyu.setProfit(BigDecimal.valueOf(0.00));
		kuyu.setRemarks(" ");
		kuyu.setResult("订购成功");
		long addTime = System.currentTimeMillis();
		kuyu.setPackage1(kuyuPackage.getName());
		kuyu.setAddtime(new Date(addTime));
		kuyu.setStarttime(TimeService.nextMonthFirstDay());
		kuyu.setEndtime(TimeService.nextMonthLastDay());
		kuyu.setStatus(2);
		String kb = "1024";
		kuyu.setSumflow(new BigDecimal(DecimalTools.mul(kuyuPackage.getFlow().toString(), kb)));
		kuyu.setType(2);
		kuyu.setUid(50);
		kuyu.setSerialNumber(" ");
		kuyu.setSource(" ");
		kuyu.setUseflow(BigDecimal.valueOf(0));
		
		kuyu.setInuse(0);
		kuyu.setLeftflow(kuyu.getSumflow());
		kuyuAddPackageService.save(kuyu);
		//kuyuAddPackageService.savePackage(kuyu);
	}
	
	/*
	 * 生成对应的扣费记录
	 */
	private void saveRecordOfDeductions(MsisdnCardMessage message, double priceDifference) {
		KuyuCardMoney kuyu = new KuyuCardMoney();
		long addTime = System.currentTimeMillis();
		kuyu.setAddtime(new Date(addTime));
		kuyu.setCard_id(message.getCardid());
		kuyu.setMoney(BigDecimal.valueOf(priceDifference));
		kuyu.setOldmoney(message.getAmount());
		kuyu.setRemarks("订购套餐");
		kuyu.setSource(" ");
		kuyu.setType(2);
		kuyu.setUid(50);
		
		kuyuCardMoneyService.save(kuyu);
	}

	private void find(MsisdnCardMessage message, KuyuPackagePrice kuyuPackagePrice) {
		// 没有订购则查询有足够余额
		// KuyuPackagePrice kuyuPackagePrice =
		// queryAmountAndOrderPrice(message,kuyuCard.getFid(),kuyuCard.getSid(),kuyuCard.getTid());
		logger.info("非02/06类号码[{}]套餐价格[{}]", message.getTel(), kuyuPackagePrice);
		if (null != kuyuPackagePrice) {
			DecimalFormat df1 = new DecimalFormat("0.00");
			// 号码账户余额
			String amount = df1.format(message.getAmount());
			// 套餐订购价格
			String packgePrice = kuyuPackagePrice.getPrice().toString();
			// 用户余额 - 套餐订购价格
			double priceDifference = DecimalTools.sub(amount, packgePrice);
			logger.info("号码[{}], 账户余额[{}], 套餐订购价格[{}], 差额[{}]", message.getTel(), amount, packgePrice, priceDifference);
			// 余额不够,停机处理
			if (Double.parseDouble(amount) <= 0 || priceDifference < 0) {
				logger.info("号码[{}], 余额[{}], 余额不够进行停机操作：", message.getTel(), amount);

				//disabledNumberController(message);;
			} else {
				logger.info("号码[{}], 扣除后余额[{}], 订购次数加1扣除余额：", message.getTel(), priceDifference);
				//orderPackage(kuyuPackagePrice, priceDifference, message);
				
				// 扣除余额
				kuyuCardService.orderForTheNextMonth(BigDecimal.valueOf(priceDifference), message.getTel());
				// 订购次数加1
				kuyuCardService.deductions(message.getFrequency() + 1, message.getTel());
				//添加返佣记录
				kuyuAgentCommission kuyu = new kuyuAgentCommission();
				long addTime = System.currentTimeMillis();
				kuyu.setAddtime(new Date(addTime));
				kuyu.setAid(kuyuPackagePrice.getAid());
				kuyu.setCardid(message.getCardid());
				kuyu.setMoney(new BigDecimal(priceDifference));
				KuyuAgentAccount queryOldMoney = kuyuAgentAccountService.queryOldMoney(kuyuPackagePrice.getAid());
				kuyu.setOldmoney(queryOldMoney.getAgo_amount());
				kuyu.setOrder_id(null);
				kuyu.setRemarks(null);
				kuyu.setUid(50);
				kuyuAgentCommissionService.save(kuyu);
				
				
				//生成对应的扣费记录
				saveRecordOfDeductions(message, priceDifference);
				saveNextMontOrder(message);
				// isStartUp(message);
			}
		}
	}

	/**
	 * 查看是否开机
	 * 
	 */
	private void isStartUp(MsisdnCardMessage message) {
		KuyuAddPackage findMonthlySumFlowsAndUseflow = kuyuAddPackageService
				.findMonthlySumFlowsAndUseflow(message.getCardid());

		if (findMonthlySumFlowsAndUseflow != null) {
			String useflow = findMonthlySumFlowsAndUseflow.getUseflow().toString();
			String sumflow = findMonthlySumFlowsAndUseflow.getSumflow().toString();
			double flow = DecimalTools.sub(sumflow, useflow);
			if (flow > 0) {
				// 开机
				// openNumberController(message);
			}
		}
	}

	/**
	 * 佣金返点
	 *
	 */
	private void commission(List<KuyuAgent> kuyuAgentList, List<kuyuAgentCommission> kuyuAgentCommissList,
			KuyuPackagePrice kuyuPackagePrice ,MsisdnCardMessage message) {
		for (KuyuAgent agen : kuyuAgentList) {
			String per = agen.getPer();
			// 0或null进行套餐返比
			if (per == null || per.equals("0")) {
				double commission;

				// 查出kuyuAgentCommission的佣金和id
				// kuyuAgentCommiss = kuyuAgentCommissionService.queryeMoney(aid);
				for (kuyuAgentCommission kuyuAgentCommiss : kuyuAgentCommissList) {
					commission = DecimalTools.sub(kuyuPackagePrice.getPrice().toString(),
							kuyuPackagePrice.getParentprice().toString());
					if (kuyuAgentCommiss != null)
						kuyuAgentService.updateAmount(Double.parseDouble(DecimalTools.add(commission, agen.getMoney())),
								kuyuPackagePrice.getAid());
					String money = DecimalTools.add(kuyuAgentCommiss.getMoney().toString(), String.valueOf(commission));
					//kuyuAgentCommissionService.updateMoney(new BigDecimal(money), kuyuAgentCommiss.getId());
					//添加返佣记录
					kuyuAgentCommission kuyu = new kuyuAgentCommission();
					long addTime = System.currentTimeMillis();
					kuyu.setAddtime(new Date(addTime));
					kuyu.setAid(kuyuPackagePrice.getAid());
					kuyu.setCardid(message.getCardid());
					kuyu.setMoney(new BigDecimal(money));
					kuyu.setOldmoney(kuyuAgentCommiss.getMoney());
					kuyu.setOrder_id(null);
					kuyu.setRemarks(null);
					kuyu.setUid(50);
					kuyuAgentCommissionService.save(kuyu);
				}
			}
		}
	}

	/**
	 * 扣除余额
	 */
/*	private void orderPackage(KuyuPackagePrice kuyuPackagePrice, double priceDifference, MsisdnCardMessage message) {
		// 扣除余额
		kuyuCardService.orderForTheNextMonth(BigDecimal.valueOf(priceDifference), message.getTel());
		// 订购次数加1
		kuyuCardService.deductions(message.getFrequency() + 1, message.getTel());

		// 分发佣金
		List<KuyuCard> findAgentMessage = kuyuCardService.findAgentMessage(message.getTel());
		// 查出kuyuAgentCommission的佣金和id
		List<kuyuAgentCommission> kuyuAgentCommissList = kuyuAgentCommissionService
				.queryeMoney(kuyuPackagePrice.getAid());
		List<KuyuAgent> agentAmount = kuyuAgentService.queryAmount(kuyuPackagePrice.getAid());

		for (KuyuCard kuyuCard : findAgentMessage) {
			// 上级定价减去最终定价为当前代理商佣金
			if (kuyuCard.getTid() != 0 || kuyuCard.getSid() != 0 || kuyuCard.getFid() != 0) {
				commission(agentAmount, kuyuAgentCommissList, kuyuPackagePrice,message);
			} else {
				logger.info("电信号码非正常卡自售号码：" + message.getTel());
			}
		}
	}
*/
	/**
	 * 查询看余额和套餐价格
	 */
	public KuyuPackagePrice queryAmountAndOrderPrice(MsisdnCardMessage message) {
		// 查询套餐价格
		/*
		 * List<KuyuPackagePrice> KuyuPackagePriceList =
		 * kuyuPackagePriceService.findPackagePriceCardMessage(message.getPackageid());
		 * if(KuyuPackagePriceList != null && KuyuPackagePriceList.size() > 0) { return
		 * KuyuPackagePriceList.get(0); }
		 */

		return null;
	}

	/**
	 * 移动号码停机处理方法
	 * 
	 * @param operator
	 * @param message
	 */
	public void disabledNumberController(MsisdnCardMessage message) {

		DisabledBean disabledBean = new DisabledBean();
		disabledBean.setActionReason("月底余额扣费停机");
		disabledBean.setSource("月底套餐监控");
		disabledBean.setCardId(message.getCardid());
		disabledBean.setIphone(message.getTel());
		disabledBean.setOperatorid(message.getOperatorid());
		disabledBean.setZid(message.getZid());
		disabledBean.setOperatorType(message.getOperator_type());
		disabledBean.setOprtype("1");
		disabledBean.setReason("6");

		disabledBean = restTemplate
				.postForEntity("http://114.55.132.207:8761/cmcc/disabledNumber", disabledBean, DisabledBean.class)
				.getBody();
		int exist = disabledBean.getResultMsg().indexOf("停机状态的用户不允许再停机");
		if ("0".equals(disabledBean.getResultCode()) || exist != -1) {
			// 成功，
			message.setCardStatus(4);
		}

	}

	public void openNumberController(MsisdnCardMessage message) {
		// 复机
		DisabledBean disabledBean = new DisabledBean();
		disabledBean.setActionReason("有流量复机");
		disabledBean.setSource("月底流量监控");
		disabledBean.setCardId(message.getCardid());
		disabledBean.setIphone(message.getTel());
		disabledBean.setOperatorid(message.getOperatorid());
		disabledBean.setZid(message.getZid());
		disabledBean.setOperatorType(message.getOperator_type());
		disabledBean.setOprtype("2");//
		disabledBean.setReason("7");//
		disabledBean = restTemplate
				.postForEntity("http://114.55.132.207:8761/cmcc/disabledNumber", disabledBean, DisabledBean.class)
				.getBody();
		if ("0".equals(disabledBean.getResultCode())) {
			// 成功
			message.setCardStatus(2);
		}
	}

}
